#import <Foundation/Foundation.h>
#import <objc/runtime.h>

#import "framework/FWCommon.h"

#import "PIIntegration.h"
#import "PIContextObject.h"


@implementation PIContextObject

@synthesize key, name, icon, color, native;


// ******************************************************************************************
#pragma mark -
#pragma mark Global sort functions

NSInteger compareContextObjectKeys(id obj1, id obj2, void *context)
{
    return [[NSNumber numberWithInt:((PIContextObject*)obj1).key] compare:[NSNumber numberWithInt:((PIContextObject*)obj2).key]];
}

NSInteger compareContextObjectNames(id obj1, id obj2, void *context)
{
    return [((PIContextObject*)obj1).name compare:((PIContextObject*)obj2).name];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

+ (PIContextObject*)objectWithKey:(NSInteger)newKey name:(NSString*)newName icon:(NSString*)newIcon color:(UIColor*)newColor native:(BOOL)newNative
{
    PIContextObject* obj = [[[PIContextObject alloc] init] autorelease];
    
    obj->key = newKey;
    obj->name = [newName copy];
    obj->icon = [newIcon copy];
    obj->color = [newColor retain];
    obj->native = newNative;
    
    return obj;
}

- (void)dealloc
{
    [name release];
    [icon release];
    [color release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Debugging functions

- (NSString*)description
{
    return [NSString stringWithFormat:
            @"<%@: %p;"
            " key = %i;"
            " name = %@;"
            " icon = %@;"
            " color = %@;"
            " native = %i>",
            [self class],
            self,
            key,
            name,
            icon,
            color,
            native];
}

@end


// ******************************************************************************************
#pragma mark -
#pragma mark Object access from arrays

@implementation NSArray (PIContextObject)

- (id)piContextObjectForKey:(NSInteger)key
{
    NSInteger count = self.count;
    for (NSInteger i = 0; i < count; ++i) {
        PIContextObject* obj = [self objectAtIndex:i];
        if (obj.key == key)
            return obj;
    }
    
    return nil;
}

- (NSString*)piContextObjectString
{
    NSMutableString* result = [NSMutableString stringWithCapacity:self.count * 10];
    NSInteger count = self.count;
    for (NSInteger i = 0; i < count; ++i) {
        PIContextObject* obj = [self objectAtIndex:i];
        [result appendString:[PIIntegration stringForTitle:obj.name withIcon:obj.icon withProjectIcon:nil] withSeparator:@", "];
    }
    
    return result;
}

@end
